package com.hope.hotel.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hope.hotel.common.Result;
import com.hope.hotel.entity.DAO.LoginDAO;
import com.hope.hotel.entity.DAO.RegisterDAO;
import com.hope.hotel.entity.DAO.TravelerDAO;
import com.hope.hotel.entity.DAO.UserInfoDAO;
import com.hope.hotel.entity.po.Traveler;
import com.hope.hotel.entity.po.User;
import com.hope.hotel.mapper.UserMapper;
import com.hope.hotel.service.UserService;
import com.hope.hotel.utils.TokenUtil;
import com.hope.hotel.utils.mail.JavaMailUntil;
import com.hope.hotel.utils.mail.SendMail;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hope.hotel.common.Result.success;

/**
 * @作者 TD
 * @日期 2025/5/18
 */

@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService   {


    private final UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result login(LoginDAO loginDAO) {
       // 查询是否存在该用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,loginDAO.getUsername());
        queryWrapper.eq(User::getPassword,loginDAO.getPassword());
        User user = baseMapper.selectOne(queryWrapper);
        if(user == null){
            return Result.error("用户名或密码错误");
        } else {
            // 返回Token
            String token = TokenUtil.generateToken(user.getUserId(), "author:TD");
            return success(token);
        }
    }

    @Override
    public Result register(RegisterDAO registerDAO) {
        // 首先验证redis中的 验证是否正确
        String code = (String)redisTemplate.opsForValue().get("emailCode:" + registerDAO.getEmail());
        if (!registerDAO.getCode().equals(code)) {
            System.out.println("code" + code);
            return Result.error("验证码错误");
        }
        System.out.println("验证码正确");
        // 然后插入数据库
        User user = BeanUtil.copyProperties(registerDAO, User.class);
        int flag = baseMapper.insert(user);
        if (flag == 1) {
            return Result.success("注册成功");
        } else
            return Result.error("注册失败");
    }

    @Override
    public Result<String> sendCode(String email) {
        try {
            // 检测邮箱是否符合
            if (!JavaMailUntil.checkEmail(email)) {

                return Result.error("邮箱格式不正确");
            }

            // 查询是否已经注册过
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, email);
            User user = baseMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(user)) {
                return Result.error("该邮箱已被注册，请换个邮箱重试！");
            }

            String code = JavaMailUntil.generateCode(4);
            // 储存进行redis验证
            System.err.println("code = " + code);
            redisTemplate.opsForValue().set("emailCode:" + email, code, 5, TimeUnit.MINUTES);  // 5分钟
            // 发送邮件
            SendMail.sendMineMessage(code, email);
        }catch (Exception e){
            return Result.error("发送失败");
        }
        return success();
    }

    @Override
    public Result checkLogin(String token) {
        // 验证token是否正确
        if (TokenUtil.validateToken(token)) {
            // 返回具体的用户信息
            String userId = TokenUtil.getUserId(token);
//            System.out.println("userId = " + userId);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUserId, userId);
            User user = userMapper.selectOne(queryWrapper);
            return Result.success(user);
        }
        return Result.error("验证失败");
    }

    @Override
    public Result addTraveler(TravelerDAO travelerDAO, String userId) {
        // 添加
        try {
            // 审查是否和标准,姓名，身份中，电话
            if(travelerDAO == null || travelerDAO.getName() == null || travelerDAO.getIdCard() == null || travelerDAO.getPhone() == null){
                return Result.error("请填写完整信息");
            }

            // 审查是否已经存在
            if(userMapper.checkTravelerIsExist(travelerDAO,userId))return Result.error("该用户已存在");

            // 审查是否合法
            if(!checkTravelerIsLegal(travelerDAO))return Result.error("信息不合法");

            Traveler traveler = BeanUtil.copyProperties(travelerDAO, Traveler.class);
            userMapper.insertTraveler(traveler, userId);
            return Result.success("添加成功");
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败");
        }
    }

    private boolean checkTravelerIsLegal(TravelerDAO travelerDAO) {
        // 姓名
        return (travelerDAO.getName().length() <= 20) && (travelerDAO.getPhone().length() == 11) && (travelerDAO.getIdCard().length() == 18);
    }

    @Override
    public Result getTravelers(String userId) {
        List<Traveler> travelers = userMapper.selectTravers(userId);
        return Result.success(travelers);
    }

    @Override
    public Result updateInfo(UserInfoDAO userInfoDAO, String userId) {
        // 更新用户（如果不变就不更新）
        User user = BeanUtil.copyProperties(userInfoDAO, User.class);
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",userId);
        int flag = baseMapper.update(user,updateWrapper);
        return flag == 1 ? Result.success("更新成功") : Result.error("更新失败");
    }

    @Override
    public Result updateTraveler(TravelerDAO travelerDAO, String userId) {
        try {
            // 验证参数
            if (travelerDAO == null || travelerDAO.getId() == null || travelerDAO.getName() == null 
                || travelerDAO.getIdCard() == null || travelerDAO.getPhone() == null) {
                return Result.error("请填写完整信息");
            }
            
            // 验证旅客是否属于当前用户
            if (!userMapper.checkTravelerBelongsToUser(travelerDAO.getId(), userId)) {
                return Result.error("无权修改此旅客信息");
            }
            
            // 验证信息合法性
            if (!checkTravelerIsLegal(travelerDAO)) {
                return Result.error("信息不合法");
            }
            
            // 更新旅客信息
            Traveler traveler = BeanUtil.copyProperties(travelerDAO, Traveler.class);
            int result = userMapper.updateTraveler(traveler);
            
            return result > 0 ? Result.success("更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result deleteTraveler(String id, String userId) {
        try {
            // 验证参数
            if (id == null || id.isEmpty()) {
                return Result.error("旅客ID不能为空");
            }
            
            // 验证旅客是否属于当前用户
            if (!userMapper.checkTravelerBelongsToUser(id, userId)) {
                return Result.error("无权删除此旅客信息");
            }
            
            // 删除旅客信息
            int result = userMapper.deleteTraveler(id);
            
            return result > 0 ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败: " + e.getMessage());
        }
    }
}
